﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Security.Cryptography;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace InfoLeech
{
    public partial class frmMain : Form
    {
        private static string configFile = configFilePath("Config.xml");
        public static string connectionStringPM;
        public static string connectionStringUser;
        // connection string naar computerlogging database = dezelfde als userlogging
        public static string connectionStringComputer;
        // nieuwe dictionary met domain lijst uit config.xml
        public static Dictionary<string, string> domainlist;

        public frmMain()
        {
            connectionStringPM = connectionString("ProcessManager");
            connectionStringUser = connectionString("UserLogging");
            connectionStringComputer = connectionString("UserLogging");
            domainlist = new Dictionary<string, string>(DomainList());
            InitializeComponent();
            lblVersion.Text = String.Format("Versie {0}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
            ctlPMtools1.FillcomboBoxReport();
            ctlADtools1.fillDomainListbox();
            showControl(ctlPMtools1);
        }

        private void btnPMtools_Click(object sender, EventArgs e)
        {
            showControl(ctlPMtools1);
        }

        private void btnADtools_Click(object sender, EventArgs e)
        {
            showControl(ctlADtools1);
        }

        private void btnUsertools_Click(object sender, EventArgs e)
        {
            showControl(ctlUserTools1);
        }

        private void btnMachinetools_Click(object sender, EventArgs e)
        {
            showControl(ctlMachineTools1);
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InfoLeech.frmAboutbox frmAbout = new InfoLeech.frmAboutbox();
            frmAbout.Show();
        }

        private void helpToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            // todo: create help file
        }

        private void showControl(Control controlToShow)
        {
            foreach (Control Cntrl in this.panelControlsRight.Controls)
            {
                if (Cntrl != controlToShow)
                {
                    Cntrl.Visible = false;
                }
            }

            if (controlToShow.Visible == false)
            {
                controlToShow.Visible = true;
            }
            controlToShow.BringToFront();
            this.Text = "InfoLeech :: " + controlToShow.AccessibleName;
        }

        public static string decryptPassword(string str)
        {
            string strKey = "!@#$%^&*()<>?/:;{}[]~`";
            return Decrypt(str, strKey);
        }

        private static string Decrypt(string strText, string sDecrKey)
        {
            byte[] byKey = null;
            byte[] IV = { 0X12, 0X34, 0X56, 0X78, 0X90, 0XAB, 0XCD, 0XEF };
            byte[] inputByteArray = new byte[strText.Length + 1];

            try
            {
                byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Convert.FromBase64String(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);

                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                System.Text.Encoding encoding = System.Text.Encoding.UTF8;

                return encoding.GetString(ms.ToArray());

            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }

        // Return the full path of the config.xml
        private static string configFilePath(string configFileName)
        {
            // string path = Environment.CurrentDirectory + "\\" + configFileName;
            string path = Application.StartupPath + "\\" + configFileName;
            // string path = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + configFileName;
            return path;
        }

        private static string connectionString(string DatabaseConnection)
        {
            string server = "";
            string database = "";
            string integratedSecurity = "";
            string username = "";
            string password = "";
            string connectionstring = "";
            if (File.Exists(configFile))
            {
                try
                {
                    XmlReader xmlReader = XmlReader.Create(configFile);

                    while (xmlReader.Read())
                    {
                        if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "Connection"))
                        {
                            if (xmlReader.HasAttributes)
                            {
                                if (xmlReader.GetAttribute("name") == DatabaseConnection)
                                {
                                    server = xmlReader.GetAttribute("server");
                                    database = xmlReader.GetAttribute("database");
                                    integratedSecurity = xmlReader.GetAttribute("integratedsecurity");
                                    username = xmlReader.GetAttribute("username");
                                    password = decryptPassword(xmlReader.GetAttribute("password"));
                                }
                            }
                        }
                    }

                    connectionstring = "Data Source=" + server + ";Initial Catalog=" + database + ";Integrated Security="
                        + integratedSecurity + ";User ID=" + username + ";Password=" + password;
                }

                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
            else
            {
                connectionstring = "";
            }

            return connectionstring;
        }

        private static Dictionary<string, string> DomainList()
        {
            Dictionary<string, string> domainlist = new Dictionary<string, string>();
            string domain = "";
            string ldapstring = "";
            if (File.Exists(configFile))
            {
                try
                {
                    XmlReader xmlReader = XmlReader.Create(configFile);

                    while (xmlReader.Read())
                    {
                        if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "Domain"))
                        {
                            if (xmlReader.HasAttributes)
                            {
                                domain = xmlReader.GetAttribute("name");
                                ldapstring = xmlReader.GetAttribute("ldapstring");
                                domainlist.Add(domain, ldapstring);
                            }
                        }
                    }

                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
            else
            {
                // domainlist is empty
            }
            return domainlist;
        }

        public void updateStatusLabel(string labelText)
        {
            StatusLabel1.Text = Convert.ToString(labelText);
        }
    }
}
